package com.xiaoxin.suma.activity;

import android.text.TextUtils;
import android.util.Log;
import android.widget.EditText;

import com.blankj.utilcode.util.ToastUtils;
import com.xiaoxin.suma.R;
import com.xiaoxin.suma.net.Api;
import com.xiaoxin.suma.net.ErrUtils;
import com.xiaoxin.suma.utils.DataManger;
import com.xiaoxin.suma.utils.RxUtil;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends BaseActivity {

    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.et_password)
    EditText etPassword;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_login;
    }

    @Override
    public boolean showActionBar() {
        return false;
    }

    @Override
    protected void initData() {
        Log.w(TAG, "initData: ");
        super.initData();
        if (!TextUtils.isEmpty(DataManger.getToken())) {
            startActivity(MainActivity.class);
            finish();
        }
    }

    @OnClick(R.id.bt_go)
    public void onViewClicked() {
        subscriptions.add(
                Api.service().login(etName.getText().toString(), etPassword.getText().toString())
                        .compose(RxUtil.rxSchedulerio_main())
                        .subscribe(this::paseData, ErrUtils::pase)
        );
    }

    private void paseData(String s) {
        boolean isLogin = false;
        switch (s) {
            case "login_error":
                s = "用户名密码错误";
                break;
            case "message|":
                s = "速度过快，请稍后再试访问速度过快，建议休眠50毫秒后再试";
                break;
            case "account_is_locked":
                s = "账号被锁定";
                break;
            case "account_is_stoped":
                s = "账号被停用";
                break;
            case "account_is_question_locked":
                s = "账号已关闭";
                break;
            case "account_is_ip_stoped":
                s = "账号ip锁定";
                break;
            case "account_is_FreezeUser":
                s = "账号被冻结";
                break;
            default:
                isLogin = true;
                String[] strings = s.split("\\|");
                if (TextUtils.equals(strings[0], etName.getText())) {
                    DataManger.setToken(strings[1]);
                    DataManger.setUserName(etName.getText().toString());
                    startActivity(MainActivity.class);
                    finish();
                }
                break;

        }
        if (!isLogin) {
            ToastUtils.showShort(s);
        }
    }
}